package com.mqqzt.douban;

import java.net.URL;

import net.htmlparser.jericho.Source;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BookDetailActivity extends Activity {
	private TextView tv_title, tv_summary;
	private LinearLayout ll_book_detail;
	private String title;
	private String summary;
	private String price;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_detail);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		tv_summary = (TextView) this.findViewById(R.id.tv_summary);
		ll_book_detail = (LinearLayout) this.findViewById(R.id.ll_book_detail);
		String isbn = getIntent().getStringExtra("isbn");
		fillData(isbn);
	}
	private void fillData(String isbn) {
		new AsyncTask<String, Void, Boolean>() {
			
			@Override
			protected void onPreExecute() {
				ll_book_detail.setVisibility(View.VISIBLE);
				super.onPreExecute();
			}

			@Override
			protected void onPostExecute(Boolean result) {
				ll_book_detail.setVisibility(View.INVISIBLE);
				tv_title.setText(title + "/" + price);
				tv_summary.setText(summary);
				super.onPostExecute(result);
			}

			@Override
			protected Boolean doInBackground(String... params) {
				//http://api.douban.com/book/subject/isbn/7543632608?alt=json
				String path = "http://api.douban.com/book/subject/isbn/" + params[0] + "?alt=json";
				try {
					URL url = new URL(path);
					Source source = new Source(url.openConnection());
					String jsonstr = source.toString();
					JSONObject jsonObj = new JSONObject(jsonstr);
					String titlestr = jsonObj.get("title").toString();
					JSONObject titleObj = new JSONObject(titlestr);
					title = titleObj.getString("$t");
					System.out.println(title);
					
					String summarystr = jsonObj.get("summary").toString();
					if(summarystr != null){
						JSONObject summaryObj = new JSONObject(summarystr);
						summary = summaryObj.getString("$t");
						System.out.println(summary);
					}
					
					String attrstr = jsonObj.getString("db:attribute");
					JSONArray array = new JSONArray(attrstr);
					for(int i = 0; i < array.length(); i++){
						JSONObject obj = new JSONObject(array.get(i).toString());
						if("price".equals(obj.getString("@name"))){
							price = obj.getString("$t");
							System.out.println(price);
						}
					}
					return true;
					
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
				
			}
		}.execute(isbn);
		
	}
}
